var RegisterForm = Class.create();

Object.extend(RegisterForm, {
	prefix: "",
	successHTML: '<img src="/image/udb/right.gif" align="middle" />',
	loadingHTML: '<span class="loading-img">正在检测中...，请稍后</span>',
	promptTemplate: '<span class="prompt prompt-span"><span class="icon-prompt">&nbsp;</span>#{string}</span>',
	emailAvailableText: 'Email可以使用',
	emailUnavailableText: 'Email已经被占用',
	nicknameAvailableText: '用户名可以使用',
	nicknameUnavailableText: '用户名被占用或格式错误',
	emailErrorText: 'Email格式错误',
	nicknameErrorText: '用户名格式错误',
	passwordErrorText: '密码太短或太长',
	password2ErrorText: '密码不一致',
	questionErrorText: '请选择一个安全问题',
	answerErrorText: '安全问题答案太短',
	vcodeErrorText: '请填写验证码',
	jumpURL: '',
	flag:false,
	exists_nickname:false,
	initHandlers: function(){
		Event.observe($("registerForm"), 'submit', this.onsubmit.bindAsEventListener(this));
		$("registerForm").enable();
		this.bindAsLister();
		this.reloadVcode();
	},
	bindAsLister:function(){
		$('email').observe('blur',this.checkEmailAvailible.bindAsEventListener(this));
		$('nickname').observe('blur',this.checkNicknameAvailible.bindAsEventListener(this));	
		$('password2').observe('blur',this.checkPasswod.bindAsEventListener(this));
	},
	onsubmit: function(event){
		event = $E(event);
		event.stop();
		if(this.checkForm()){
			this.dosubmit();
		}else{
			alert('您填写的信息有误，请按提示修改后再提交。');
		}
	},
	reloadVcode: function(){
		$(this.prefix + "vcodeimg").src= "/v.php?_act=gen&"+Math.random();
		$(this.prefix + "vcode").value = "";
	},
	checkEmailAvailible: function(){
		var email = $('registerForm')[this.prefix + 'email'].value;
		var field = $$('#emailField .check')[0]; 
//		var btn = $('checkemailBtn');
		var template = new Template(this.promptTemplate);
		if(!this.checkEmail(email)){
			field.innerHTML = template.evaluate({string: this.emailErrorText});
			this.flag = true;
			return ;
		}

		field.innerHTML = this.loadingHTML;
//		btn.disabled = true;
		
		new Ajax.Request("/~member.index.chkemail",{
			method: "POST",
			parameters: $H({email: email}).toQueryString(),
			onComplete: function(transporter){
				var ret = transporter.responseText.evalJSON();
				if(ret["result"]){
					field.innerHTML = template.evaluate({string: this.emailAvailableText});
				}else{
					field.innerHTML = template.evaluate({string: this.emailUnavailableText});
					this.flag = true;
				}
//				btn.disabled = false;
			}.bindAsEventListener(this)
		});
	},
	checkNicknameAvailible: function(){
		var nickname = $('registerForm')[this.prefix + 'nickname'].value;
		var field = $$('#nicknameField .check')[0];
//		var btn = $('checknicknameBtn');
		var template = new Template(this.promptTemplate);
		
		if(!this.checkNickname(nickname)){
			field.innerHTML = template.evaluate({string: this.nicknameErrorText});
			this.flag = true;
			return;
		}
		
		field.innerHTML = this.loadingHTML;
//		btn.disabled = true;
		
		new Ajax.Request("/~member.index.chkname",{
			method: "POST",
			parameters: $H({username: nickname}).toQueryString(),
			onComplete: function(transporter){
				var ret = transporter.responseText.evalJSON();
				if(ret["result"]){
					field.innerHTML = template.evaluate({string: this.nicknameAvailableText});
				}else{
					field.innerHTML = template.evaluate({string: this.nicknameUnavailableText});
					this.flag = true;
				}
//				btn.disabled = false;
			}.bindAsEventListener(this)
		});
	},
	checkForm: function(){
		var ret = true;
		var flag = false;
		
		var template = new Template(this.promptTemplate);
		
		if(this.flag){
//			$$('#emailField .check')[0].innerHTML = template.evaluate({string: this.emailUnavailableText});
			flag = false;
		}
		
		// 检查email
		var field = $$("#emailField .check")[0];
		if($('registerForm')[this.prefix + "email"].value.trim() == ""){
			flag = false;
			field.innerHTML = template.evaluate({string: this.emailErrorText});
		}
		else if(!(flag = this.checkEmail($('registerForm')[this.prefix + "email"].value))){
			field.innerHTML = template.evaluate({string: this.emailErrorText});
		}else{
			field.innerHTML = this.successHTML;
		}
		ret = ret && flag;
		
		// 检查用户名
		field = $$("#nicknameField .check")[0];
		if($('registerForm')[this.prefix + "nickname"].value.trim() == ""){
			flag = false;
			field.innerHTML = template.evaluate({string: this.nicknameErrorText});
		}
		else if(!(flag = this.checkNickname($('registerForm')[this.prefix + "nickname"].value))){
			field.innerHTML = template.evaluate({string: this.nicknameErrorText});
		}else{
			field.innerHTML = this.successHTML;
		}
		ret = ret && flag;

		// 检查密码	
		field = $$("#passwordField .check")[0];
		if($('registerForm')[this.prefix + "password"].value.trim().length < 6 || $('registerForm')[this.prefix + "password"].value.trim().length > 32){
			flag = false;
			field.innerHTML = template.evaluate({string: this.passwordErrorText});
		}else{
			field.innerHTML = this.successHTML;
			
			field = $$("#password2Field .check")[0];
			if($('registerForm')[this.prefix + "password"].value.trim() != $('registerForm')[this.prefix + "password2"].value.trim()){
				flag = false;
				field.innerHTML = template.evaluate({string: this.password2ErrorText});
			}else{
				field.innerHTML = this.successHTML;
			}
		}
		ret = ret && flag;
			
		// 检查验证码
		field = $$("#vcodeField .check")[0];
		if($('registerForm')[this.prefix + "vcode"].value.trim() == ""){
			flag = false;
			field.innerHTML = template.evaluate({string: this.vcodeErrorText});
		}
		else if(!(flag = this.checkVcode($('registerForm')[this.prefix + "vcode"].value))){
			field.innerHTML = template.evaluate({string: this.vcodeErrorText});
		}else{
			field.innerHTML = this.successHTML;
		}
		ret = ret && flag;
		
		return ret;
		
	},
	checkPasswod:function(){
		var template = new Template(this.promptTemplate);
		if($('registerForm')[this.prefix + "password"].value.trim() != $('registerForm')[this.prefix + "password2"].value.trim()){
			$$("#password2Field .check")[0].innerHTML = template.evaluate({string: this.password2ErrorText});
		}else{
			$$("#password2Field .check")[0].innerHTML = template.evaluate({string: '密码输入正确'});
		}
	},
	dosubmit: function(){
		//this.showMessage(this.loadingHTML);
		var form = this;
		var template = new Template(this.promptTemplate);
		$(this.prefix + "submitBtn").disabled = true;
		$("registerForm").request({
			onComplete: function(transport){
				try{
					var ret = transport.responseText.evalJSON();
					if(ret.result){
						form.regSuccess(ret.data, $('registerForm')[this.prefix + "email"].value, $('registerForm')[this.prefix + "nickname"].value, $('registerForm')[this.prefix + "password"].value);
						return;
					}else{
						ret.reason.each(function(v){
							var field = $$("#"+v.src+"Field .check")[0];
							field.innerHTML = template.evaluate({string: v.msg});
						});
						alert('您填写的信息有误，请按提示修改后再提交。');
					}
					this.reloadVcode();
					$(this.prefix + "submitBtn").disabled = false;
				}catch(e){
					this.reloadVcode();
					$(this.prefix + "submitBtn").disabled = false;
				}
			}.bindAsEventListener(this)
		});
		
	},
	regSuccess: function(uid, username, email, password){
		var loginForm = $('loginForm');
		loginForm.email.value = uid;
		loginForm.password.value = password;
		loginForm.submit();
	},
	checkNickname:function(str){
		return true;
	},
	checkPassword:function(password1, password2){
		return (password1.length>=6) && (password1 == password2);
	},
	checkEmail:function(str){
		return /^\w+(?:[-+.]\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*$/.test(str);
	},
	checkProcotol: function(checked){
		return checked;
	},
	checkQuestion: function(question){
		if(question.options[question.selectedIndex].value.trim()==''){
			return false
		}else{
			return true;
		}
	},
	checkAnswer: function(str){
		return str.length >= 2;
	},
	checkVcode:function(str){
		return str.length==4;
	},
	goNext: function(){
		location.href = 'activate.php';
	},
	initModNickname: function(){
		$('modNicknameForm').observe('submit', this.modNickname.bindAsEventListener(this));
	},
	modNickname: function(event){
		event = $E(event);
		event.stop();
		
		var nickname = $('nickname').value.trim();
		var field = $$("#nicknameField .check")[0];
		var template = new Template(this.promptTemplate);
		if(!this.checkNickname(nickname)){
			field.innerHTML = this.nicknameErrorText;
			return;
		}
		
		var form = $('modNicknameForm');
		form.request({
			onComplete: function(transport){
				try{
					var ret = transport.responseText.evalJSON();
					if(ret.result){
						$('dis_nickname').innerHTML = nickname;		
						$('modNicknameForm').hide();			
					}else{
						ret.reason.each(function(v){
							field.innerHTML = v.msg;
						});
					}
				}catch(e){
					alert(e.message);
				}
			}
		});
	},
	initModEmail: function(){
		$('modEmailForm').observe('submit', this.modEmail.bindAsEventListener(this));
	},
	modEmail: function(event){
		event = $E(event);
		event.stop();
		
		var email = $('email').value.trim();
		var field = $$("#emailField .check")[0];
		var template = new Template(this.promptTemplate);
		if(!this.checkEmail(email)){
			field.innerHTML = this.emailErrorText;
			return;
		}
		
		var form = $('modEmailForm');
		form.request({
			onComplete: function(transport){
				try{
					var ret = transport.responseText.evalJSON();
					if(ret.result){
						$('dis_email').innerHTML = email;		
						$('modEmailForm').hide();			
					}else{
						ret.reason.each(function(v){
							field.innerHTML = v.msg;
						});
					}
				}catch(e){
					alert(e.message);
				}
			}
		});
	},
    checkLoginForm:function(){
        if($('user_name').value.strip() == ''){
            alert('用户名不能为空！');
            $('user_name').focus();
            return false;
        }
        if($('user_pwd').value.strip() == ''){
            alert('密码不能为空！');
            $('user_pwd').focus();
            return false;
        }
        if($('vcode').value.strip() == ''){
            alert('验证码不能为空！');
            $('vcode').focus();
            return false;
        }
        return true;
	}
});

//Object.extend(RegisterForm, Message);